import axios from 'axios'
import Vue from 'vue'
// import router from 'vue-router'

axios.defaults.timeout = 3000;
// axios.defaults.withCredentials = true;

let vue = new Vue();



axios.interceptors.request.use(
    config => {
        if (config.url == '/api/login' ||
         config.url == '/api/user/login' ||
         config.url == '/api/user/logup' ||
         config.url == '/api/user/sendtele' ||
         config.url == '/api/user/restpaw'
         ) {
            return config
        }
        let token = localStorage.getItem('User-Token');
        
        if (!token) {
            window.location.href = '/login'
            //还没有token,跳转。
            return;
        }
        config.headers['User-Token'] = token;
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);


axios.interceptors.response.use(
    response => {
        if (response) {
            switch (response.data.code) {
                // 对得到的状态码的处理，具体的设置视自己的情况而定
                case 408:
                    // alert('异地登录')
                    vue.$message({
                        message: '异地登录',
                        type:'error'
                    })
                    localStorage.removeItem('User-Token')
                    window.location.href = '/login'
                    break
                case 407:
                    vue.$message({
                        message: '登录超时',
                        type:'error'
                    })
                    localStorage.removeItem('User-Token')
                    window.location.href = '/login'

                    break
            }
        }
        if (response.headers['user-token']) {
            localStorage.setItem('User-Token', response.headers['user-token']);
        }

        return Promise.resolve(response.data);
    },
    error => {

        return Promise.reject(error);
    }
);

export default {
    get(url, params, headers) {
        let options = {}
        if (params) options.params = params;
        if (headers) options.headers = headers;
        return new axios.get(url, options)
    },

    post(url, data, headers) {
        let options = {}
        if (headers) options.headers = headers;
        return axios.post(url, data, options)
    }
}
